//
//  CommunityViewController.m
//  FAKER
//
//  Created by Jianwei on 15/11/2.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "CommunityViewController.h"
#import "AllHeader.h"
#import "FitHeader.h"

#define URLSTRING @"http://dis.myzaker.com/api/get_post_selected.php?_appid=iphone"
#define REDCOLOR [UIColor colorWithRed:0.97 green:0.29 blue:0.27 alpha:1]

@interface CommunityViewController ()<UIScrollViewDelegate, YHScrollToTopDelegate, YHShowAlertViewDelegate, YHJumpDelegate, YHRemoveLoadingViewDelegate>
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)YHScrollToTopButtonView *scrollToTopButton;
@property(nonatomic, strong)UIView *backgroundLineView;
@property(nonatomic, assign)NSInteger currentIndex;
@property(nonatomic, strong)NSArray *itemLabelArray;
@property(nonatomic, strong)YHLoadingView *loadingView;
@property(nonatomic, strong)UIView *navigationBarView;
@property(nonatomic, strong)UILabel *titleLabel;
#pragma mark 关注collectionView
@property(nonatomic, strong)YHFocusCollectionView *focusCollectionView;
@property(nonatomic, strong)UIImageView *nothingImageView;
#pragma mark 精选tableView
@property(nonatomic, strong)YHSelectedTableView *selectedTableView;
@property(nonatomic, strong)UILabel *focusLabel;
@property(nonatomic, strong)UILabel *selectedLabel;
@property(nonatomic, strong)UILabel *discoveryLabel;
@property(nonatomic, strong)UIView *redLineView;//红色底线
@property(nonatomic, strong)NSArray *itemNameArray;
@property(nonatomic, strong)NSArray *itemNameColorArray;//关注/精选/发现 字体颜色数组
#pragma mark 发现tableView
@property(nonatomic, strong)YHDiscoveryTableView *discoveryTableView;
@end

@implementation CommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"社区";
    _currentIndex = 1;
    _itemLabelArray = [NSArray arrayWithObjects:_focusLabel, _selectedLabel, _discoveryLabel, nil];
    
    self.navigationController.navigationBar.bounds = CGRectMake(0, 64, 0, 0);
    self.navigationController.navigationBar.hidden = 1;
    self.navigationController.automaticallyAdjustsScrollViewInsets = 0;
    self.automaticallyAdjustsScrollViewInsets = 0;
    _navigationBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:_navigationBarView];
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 20 * FITWIDTH, 22, 40 * FITWIDTH, 40)];
    _titleLabel.text = @"社区";
    _titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [_navigationBarView addSubview:_titleLabel];
    
    //创建暂无关注
    [self createNothingImageView];
    
    //添加夜间模式监听
    [self changeColor];
    ADD_NSNOTIFICATIONCENTER_OBSERVER;
    
    //创建加载中视图
    _loadingView = [[YHLoadingView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49 + 40)];
    [self.view addSubview:_loadingView];
}

#pragma mark - 移除加载中视图
- (void)yhRemoveLoadingView
{
    [_loadingView removeFromSuperview];
}

#pragma mark - 创建视图
- (void)loadView
{
    [super loadView];
    //创建顶部itemLabel
    [self createItemLabel];
    
    //创建底部滚动视图
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 40 + 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49 - 40)];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 3, _scrollView.HEIGHT);
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    _scrollView.bounces = NO;
    [self.view addSubview:_scrollView];
    
    //创建精选tableView
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        _selectedTableView = [[YHSelectedTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, _scrollView.HEIGHT) URLString:URLSTRING];
        _selectedTableView.loadingDelegate = self;
        void (^scrollToTopBlock)(CGFloat) = ^(CGFloat y) {
            if (y > SCREEN_HEIGHT) {
                _scrollToTopButton.hidden = NO;
            }
            else if (y < SCREEN_HEIGHT) {
                _scrollToTopButton.hidden = YES;
            }
        };
        _selectedTableView.scrollToTopBlock = scrollToTopBlock;
        [_scrollView addSubview:_selectedTableView];
        
        //创建返回顶部按钮
        [self createScrollToTopButtonView];
    });

    //创建关注tableView
    _focusCollectionView = [[YHFocusCollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _scrollView.HEIGHT)];
    _focusCollectionView.jumpDelegate = self;
    [_scrollView addSubview:_focusCollectionView];
    
    //创建发现tableView
    _discoveryTableView = [[YHDiscoveryTableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 2, 0, SCREEN_WIDTH, _scrollView.HEIGHT)];
    _discoveryTableView.delegate = self;
    [_scrollView addSubview:_discoveryTableView];
}
#pragma mark 创建顶部 关注/精选/发现
- (void)createItemLabel
{
    _itemNameArray = [NSArray arrayWithObjects:@"关注", @"精选", @"发现", nil];
    [self changeItemNameColorArray];
    
    //创建 关注/精选/发现
    for (NSInteger i = 0; i < 3; i++) {
        UILabel *itemLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 3 * i, 64, SCREEN_WIDTH / 3, 40)];
        itemLabel.text = _itemNameArray[i];
        itemLabel.font = [UIFont systemFontOfSize:15];
        itemLabel.textAlignment = NSTextAlignmentCenter;
        itemLabel.tag = 1000 + i;
        itemLabel.userInteractionEnabled = YES;
        
        //点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickItemLabelAction:)];
        [itemLabel addGestureRecognizer:tap];
        [self.view addSubview:itemLabel];
        
        switch (i) {
            case 0:
                itemLabel.textColor = _itemNameColorArray[0];
                _focusLabel = itemLabel;
                break;
            case 1:
                itemLabel.textColor = _itemNameColorArray[1];
                _selectedLabel = itemLabel;
                break;
                
            default:
                itemLabel.textColor = _itemNameColorArray[0];
                _discoveryLabel = itemLabel;
                break;
        }
    }
    //灰色底线
    _backgroundLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39 + 64, SCREEN_WIDTH, 1)];
    [self.view addSubview:_backgroundLineView];
    //创建 关注/精选/发现 红色底线
    _redLineView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 3, 38 + 64, SCREEN_WIDTH / 3, 2)];
//    _redLineView.backgroundColor = [UIColor colorWithRed:0.97 green:0.29 blue:0.27 alpha:1];
    [self.view addSubview:_redLineView];
}

#pragma mark - 点击方法
#pragma mark 点击 关注/精选/发现 方法
- (void)clickItemLabelAction:(UITapGestureRecognizer *)tap
{
    [self itemLabelActWithIndex:tap.view.tag - 1000 ViewScroll:YES];
}
#pragma mark itemLabel动作表现
- (void)itemLabelActWithIndex:(NSInteger)index ViewScroll:(BOOL)scroll
{
    if (index == 0) {
        [UIView animateWithDuration:.2 animations:^{
            //刷新关注collectionView
            _focusCollectionView.isReloadData = YES;
            [self nothingAction];
            if (scroll) {
                _redLineView.frame = CGRectMake(0, 38 + 64, SCREEN_WIDTH / 3, 2);
            }
            _scrollView.contentOffset = CGPointMake(0, 0);
            _focusLabel.textColor = _itemNameColorArray[1];
            _selectedLabel.textColor = _itemNameColorArray[0];
            _discoveryLabel.textColor = _itemNameColorArray[0];
        }];
    }
    else if (index == 1) {
        [UIView animateWithDuration:.2 animations:^{
            if (scroll) {
                _redLineView.frame = CGRectMake(SCREEN_WIDTH / 3, 38 + 64, SCREEN_WIDTH / 3, 2);
            }
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
            _focusLabel.textColor = _itemNameColorArray[0];
            _selectedLabel.textColor = _itemNameColorArray[1];
            _discoveryLabel.textColor = _itemNameColorArray[0];
        }];
    }
    else {
        [UIView animateWithDuration:.2 animations:^{
            if (scroll) {
                _redLineView.frame = CGRectMake(SCREEN_WIDTH / 3 * 2, 38 + 64, SCREEN_WIDTH / 3, 2);
            }
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH * 2, 0);
            _focusLabel.textColor = _itemNameColorArray[0];
            _selectedLabel.textColor = _itemNameColorArray[0];
            _discoveryLabel.textColor = _itemNameColorArray[1];
        }];
    }
    
    //itemLabel当前坐标
    _currentIndex = index;
}

#pragma mark - scrollView协议方法
#pragma mark 滚动停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = 0;
    if (_scrollView.contentOffset.x > SCREEN_WIDTH / 2 && _scrollView.contentOffset.x < SCREEN_WIDTH + SCREEN_WIDTH / 2) {
        index = 1;
    }
    else if (_scrollView.contentOffset.x < SCREEN_WIDTH / 2) {
        index = 0;
    }
    else {
        index = 2;
    }
    //根据index判断itemLabel动作
    [self itemLabelActWithIndex:index ViewScroll:YES];
}

#pragma mark - 创建返回顶部按钮
- (void)createScrollToTopButtonView
{
    _scrollToTopButton = [[YHScrollToTopButtonView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 2 - 45, _scrollView.HEIGHT - 45, 35, 35)];
    _scrollToTopButton.delegate = self;
    _scrollToTopButton.hidden = YES;
    [_scrollView addSubview:_scrollToTopButton];
}
#pragma mark 返回顶部协议方法
- (void)yhScrollToTop
{
    [_selectedTableView.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 显示alertView协议方法
- (void)yhShowAlertViewWithStatus:(BOOL)status
{
    NSString *message = @"关注成功!";
    if (!status) {
        message = @"取消关注";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:^{
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
}

#pragma mark - 关注界面协议跳转
- (void)yhJump:(Focus *)focus
{
    YHTopicViewController *topicVC = [[YHTopicViewController alloc] init];
    topicVC.urlString = focus.api_url;
    topicVC.topicName = focus.title;
    topicVC.coverImageURL = focus.pic;
    
    topicVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:topicVC animated:YES];
}

#pragma mark - 视图即将出现判断是否添加关注或取消关注
- (void)viewDidAppear:(BOOL)animated
{
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [_discoveryTableView.tableView reloadData];
    _focusCollectionView.isReloadData = YES;
    
    //判断是否暂无关注
    [self nothingAction];
}

#pragma mark - 创建暂无关注
- (void)createNothingImageView
{
    _nothingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200 * FITWIDTH, 130 * FITHEIGHT)];
    _nothingImageView.center = CGPointMake(_scrollView.center.x, _scrollView.HEIGHT / 2);
    _nothingImageView.contentMode = UIViewContentModeScaleAspectFit;
    _nothingImageView.image = [UIImage imageNamed:@"circle_prompt_empty_following@2x"];
    [_scrollView addSubview:_nothingImageView];
    [self nothingAction];
}
#pragma mark 判断是否暂无关注
- (void)nothingAction
{
    if (!_focusCollectionView.dataSourceArray.count) {
        _nothingImageView.alpha = 1;
    }
    else {
        _nothingImageView.alpha = 0;
    }
}

#pragma mark - 点击发现cell进入topicVC
- (void)yhClickEnterIntoTopicVC:(YHDiscovery *)discovery
{
    YHTopicViewController *topicVC = [[YHTopicViewController alloc] init];
    
    topicVC.urlString = discovery.api_url;
    topicVC.topicName = discovery.title;
    topicVC.coverImageURL = discovery.pic;
    
    topicVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:topicVC animated:YES];
}

#pragma mark - 夜间模式改变颜色
- (void)changeColor
{
    if (NSUSERDEFAULTS_NIGHT) {
        _backgroundLineView.backgroundColor = [UIColor darkGrayColor];
        _redLineView.backgroundColor = [UIColor lightGrayColor];
        _navigationBarView.backgroundColor = BGCOLOR_BLACK;
        _titleLabel.textColor = [UIColor lightGrayColor];
    } else {
        _backgroundLineView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
        _redLineView.backgroundColor = REDCOLOR;
        _navigationBarView.backgroundColor = BGCOLOR_RED;
        _titleLabel.textColor = [UIColor whiteColor];
    }
    [self changeItemNameColorArray];
    for (NSInteger i = 0; i < 3; i++) {
        UILabel *itemLabel = _itemLabelArray[i];
        if (i == _currentIndex) {
            itemLabel.textColor = _itemNameColorArray[1];
        } else {
            itemLabel.textColor = _itemNameColorArray[0];
        }
    }
}

- (void)changeItemNameColorArray
{
    if (NSUSERDEFAULTS_NIGHT) {
        _itemNameColorArray = [NSArray arrayWithObjects:[UIColor darkGrayColor], [UIColor lightGrayColor], nil];
    } else {
        _itemNameColorArray = [NSArray arrayWithObjects:[UIColor grayColor], REDCOLOR, nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
